//
//  LSLoginViewController.m
//  LaSaCivilAffairsDepartment
//
//  Created by 聂志康 on 2018/12/18.
//  Copyright © 2018 wpkj. All rights reserved.
//

#import "LSLoginViewController.h"
#import "LSForgetPasswordViewController.h"
#import "LSWaveView.h"
#import "UUID.h"

#define WaveViewHeight 32
#define SecondWaveViewHeight 30
#define ThirdWaveViewHeight 47
#define FourthWaveViewHeight 47

@interface LSLoginViewController () <UITextFieldDelegate>
@property (nonatomic, strong) UIImageView *headerView;
@property (nonatomic, strong) LSWaveView *firstWaveView;
@property (nonatomic, strong) LSWaveView *secondWaveView;
@property (nonatomic, strong) LSWaveView *thirdWaveView;
@property (nonatomic, strong) LSWaveView *fourthWaveView;
@property (nonatomic, strong) UITextField *userNameTF;
@property (nonatomic, strong) UITextField *passwordTF;
@property (nonatomic, strong) UIButton *loginButton;
@property (nonatomic, strong) UIButton *remeberMeButton;
@property (nonatomic, strong) UIButton *forgetPasswordButton;
@end

@implementation LSLoginViewController

- (void)viewDidLoad {
    [super viewDidLoad];
    //单独设置背景色
    self.view.backgroundColor = UIColor.whiteColor;
    //头部视图
    //5DCCF2---349AD0从上至下渐变色
    UIImageView *headerView = [[UIImageView alloc] initWithFrame:CGRectMake(0, 0, ScreenWidth, 240+(SafeAreaTopHeight-64+20))];
    self.headerView = headerView;
    headerView.image = [UIImage gradientColorImageFromColors:@[hexColor(5DCCF2),hexColor(349AD0)] gradientType:GradientTypeTopToBottom imgSize:CGSizeMake(ScreenWidth, 240+(SafeAreaTopHeight-64+20))];
    UIImageView *iconImageView = [[UIImageView alloc] initWithFrame:CGRectMake(ScreenWidth/2-34, 55+(SafeAreaTopHeight-64+20), 68, 68)];
    iconImageView.image = [UIImage imageNamed:@"logo"];
    [headerView addSubview:iconImageView];
    [headerView addSubview:[[UILabel alloc] initWithFrame:CGRectMake(0, CGRectGetMaxY(iconImageView.frame)+10, ScreenWidth, 23) andText:@"智 慧 民 政" andTextColor:UIColor.whiteColor andFont:[UIFont fontWithName:@"SourceHanSansCN-Medium" size:23] andTextAlignment:NSTextAlignmentCenter]];
    [self.view addSubview:headerView];
    //波浪
    [self.view addSubview:self.fourthWaveView];
    [self.view addSubview:self.thirdWaveView];
    [self.view addSubview:self.secondWaveView];
    [self.view addSubview:self.firstWaveView];
    //输入框
    [self.view addSubview:self.userNameTF];
    [self.view addSubview:self.passwordTF];
    //登录按钮
    [self.view addSubview:self.loginButton];
    //记住我和忘记密码
    [self.view addSubview:self.remeberMeButton];
//    [self.view addSubview:self.forgetPasswordButton];
//    self.userNameTF.text = @"admin";
//    self.passwordTF.text = @"123456";
}

#pragma mark - 登录按钮点击事件
- (void)loginButtonClick {
//    [self.view endEditing:YES];
//    [[NSNotificationCenter defaultCenter] postNotificationName:UINotificationLoginSucceedMessageName object:nil];
//    [self dismissViewControllerAnimated:true completion:nil];
//    return;
    NSString *newStr= [self.userNameTF.text stringByReplacingOccurrencesOfString:@" " withString:@""];
    if ([newStr isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请输入用户名"];
        return;
    } else if ([self.passwordTF.text isEqualToString:@""]) {
        [MBProgressHUD showTipMessageInWindow:@"请输入密码"];
        return;
    }
    [self.fourthWaveView.wavesDisplayLink invalidate];
    [self.thirdWaveView.wavesDisplayLink invalidate];
    [self.secondWaveView.wavesDisplayLink invalidate];
    [self.firstWaveView.wavesDisplayLink invalidate];
    NSString *uuID = [UUID getUUID];

    NSDictionary *param = @{@"username":newStr,@"password":self.passwordTF.text,@"imeino":uuID};
    MBProgressHUD *hud = [MBProgressHUD showHUDAddedTo:self.view animated:true];
    [NetworkUtils requestNOHandleWithMethod:@"POST" URL:UserLogin param:param completionHandler:^(id responseObject, NSError *connectionError) {
        [hud hideAnimated:true];
        if (!connectionError) {
            NSLog(@"返回数据----%@",responseObject);
            [UserInfoModel sharedInstance].token = [ValidateUtils validateNull:responseObject[@"token"]];
            NSDictionary *dataDict = responseObject[@"data"];
            if (dataDict && dataDict.count > 0) {
                [UserInfoModel sharedInstance].customerRealName = [ValidateUtils validateNull:dataDict[@"realName"]];
                [UserInfoModel sharedInstance].customerNickname = [ValidateUtils validateNull:dataDict[@"userName"]];
                [UserInfoModel sharedInstance].customerId = [ValidateUtils validateNull:dataDict[@"id"]];
                [UserInfoModel sharedInstance].departid = [ValidateUtils validateNull:dataDict[@"departid"]];
                [UserInfoModel sharedInstance].isLogin = true;
                NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
                if ([defaults objectForKey:@"doRememberMe"]) {
                    [defaults setObject:self.userNameTF.text forKey:UserLoginNameKey];
                    [defaults setObject:self.passwordTF.text forKey:UserLoginPasswordKey];
                } else {
                    [defaults removeObjectForKey:UserLoginNameKey];
                    [defaults removeObjectForKey:UserLoginPasswordKey];
                }
                [[NSNotificationCenter defaultCenter] postNotificationName:UINotificationLoginSucceedMessageName object:nil];
                [self dismissViewControllerAnimated:true completion:nil];
                [MBProgressHUD showTipMessageInWindow:@"登录成功"];
            } else {
                if (![[ValidateUtils validateNull:responseObject[@"resultMsg"]] isEqualToString:@""]) {
                    [MBProgressHUD showTipMessageInWindow:responseObject[@"resultMsg"]];
                } else if (![[ValidateUtils validateNull:responseObject[@"msg"]] isEqualToString:@""]) {
                    [MBProgressHUD showTipMessageInWindow:responseObject[@"msg"]];
                } else if (![[ValidateUtils validateNull:responseObject[@"message"]] isEqualToString:@""]) {
                    [MBProgressHUD showTipMessageInWindow:responseObject[@"message"]];
                } else {
                    [MBProgressHUD showTipMessageInWindow:@"未知错误"];
                }
            }
        } else {
            [MBProgressHUD showTipMessageInWindow:connectionError.localizedDescription];
        }
    }];
}

#pragma mark - 记住我按钮点击事件
- (void)remeberMeButtonClick:(UIButton *)button {
    button.selected = button.isSelected?false:true;
    NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
    if (button.isSelected) {
        [defaults setBool:YES forKey:@"doRememberMe"];
    } else {
        [defaults setBool:NO forKey:@"doRememberMe"];
        [defaults removeObjectForKey:UserLoginNameKey];
        [defaults removeObjectForKey:UserLoginPasswordKey];
    }
    [defaults synchronize];
}

#pragma mark - 忘记密码按钮点击事件
- (void)forgetPasswordButtonClick {
    LSForgetPasswordViewController *forgetPasswordVC = [[LSForgetPasswordViewController alloc] init];
    [self.navigationController pushViewController:forgetPasswordVC animated:true];
}

//设置账号文本框全部删除后密码也清除
- (BOOL)textField:(UITextField *)textField shouldChangeCharactersInRange:(NSRange)range replacementString:(NSString *)string {
    NSString * str = [textField.text stringByReplacingCharactersInRange:range withString:string];
    if (textField == self.userNameTF && [str isEqualToString:@""]) {
        self.passwordTF.text = @"";
    }
    return YES;
}

- (UITextField *)userNameTF {
    if (!_userNameTF) {
        _userNameTF = [[UITextField alloc] initWithFrame:CGRectMake(52, CGRectGetMaxY(self.headerView.frame)+40, ScreenWidth-104, 50)];
        _userNameTF.layer.cornerRadius = 8;
        _userNameTF.delegate = self;
        _userNameTF.layer.masksToBounds = true;
        _userNameTF.layer.borderColor = hexColor(666666).CGColor;
        _userNameTF.layer.borderWidth = 0.5;
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, 40, 30)];
        UIImageView *leftViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(6, 0, 30, 30)];
        leftViewImageView.tintColor = hexColor(666666);
        UIImage *yhmImage = [[UIImage imageNamed:@"yhm"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        leftViewImageView.image = yhmImage;
        [leftView addSubview:leftViewImageView];
        _userNameTF.leftView = leftView;
        _userNameTF.leftViewMode = UITextFieldViewModeAlways;
        _userNameTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入用户名" attributes:@{NSForegroundColorAttributeName:hexColor(999999),NSFontAttributeName:[UIFont systemFontOfSize:15]}];
        _userNameTF.attributedPlaceholder = attrString;
        _userNameTF.secureTextEntry = false;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults boolForKey:@"doRememberMe"]) {
            _userNameTF.text = [defaults objectForKey:UserLoginNameKey];
        }
    }
    return _userNameTF;
}

- (UITextField *)passwordTF {
    if (!_passwordTF) {
        _passwordTF = [[UITextField alloc] initWithFrame:CGRectMake(52, CGRectGetMaxY(self.userNameTF.frame)+9, ScreenWidth-104, 50)];
        _passwordTF.layer.cornerRadius = 8;
        _passwordTF.layer.masksToBounds = true;
        _passwordTF.layer.borderColor = hexColor(666666).CGColor;
        _passwordTF.layer.borderWidth = 0.5;
        UIView *leftView = [[UIView alloc] initWithFrame:CGRectMake(0, 10, 40, 30)];
        UIImageView *leftViewImageView = [[UIImageView alloc] initWithFrame:CGRectMake(6, 0, 30, 30)];
        UIImage *mimaImage = [[UIImage imageNamed:@"mima"] imageWithRenderingMode:UIImageRenderingModeAlwaysTemplate];
        leftViewImageView.image = mimaImage;
        leftViewImageView.tintColor = hexColor(666666);
        [leftView addSubview:leftViewImageView];
        _passwordTF.leftView = leftView;
        _passwordTF.leftViewMode = UITextFieldViewModeAlways;
        _passwordTF.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:15];
        NSAttributedString *attrString = [[NSAttributedString alloc] initWithString:@"请输入密码" attributes:@{NSForegroundColorAttributeName:hexColor(999999),NSFontAttributeName:[UIFont systemFontOfSize:15]}];
        _passwordTF.attributedPlaceholder = attrString;
        _passwordTF.secureTextEntry = true;
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults boolForKey:@"doRememberMe"]) _passwordTF.text = [defaults objectForKey:UserLoginPasswordKey];
    }
    return _passwordTF;
}

- (UIButton *)loginButton {
    if (!_loginButton) {
        _loginButton = [[UIButton alloc] initWithFrame:CGRectMake(52, CGRectGetMaxY(self.passwordTF.frame)+40, ScreenWidth-104, 40)];
        _loginButton.backgroundColor = hexColor(36baf7);
        _loginButton.layer.cornerRadius = 8;
        _loginButton.layer.masksToBounds = true;
        _loginButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:16];
        [_loginButton setTitle:@"登 录" forState:UIControlStateNormal];
        [_loginButton setTitleColor:UIColor.whiteColor forState:UIControlStateNormal];
        [_loginButton addTarget:self action:@selector(loginButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _loginButton;
}

- (UIButton *)remeberMeButton {
    if (!_remeberMeButton) {
        _remeberMeButton = [[UIButton alloc] initWithFrame:CGRectMake(52, CGRectGetMaxY(self.passwordTF.frame), 120, 32)];
        [_remeberMeButton setImage:[UIImage imageNamed:@"remeberMe"] forState:UIControlStateNormal];
        [_remeberMeButton setImage:[UIImage imageNamed:@"remeberMe_selected"] forState:UIControlStateSelected];
        [_remeberMeButton setTitle:@"记住账号密码" forState:UIControlStateNormal];
        [_remeberMeButton setTitleColor:hexColor(333333) forState:UIControlStateNormal];
        _remeberMeButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:13];
        [_remeberMeButton addTarget:self action:@selector(remeberMeButtonClick:) forControlEvents:UIControlEventTouchUpInside];
        [_remeberMeButton setImageEdgeInsets:UIEdgeInsetsMake(0, 0, 0, 8)];
        NSUserDefaults *defaults = [NSUserDefaults standardUserDefaults];
        if ([defaults boolForKey:@"doRememberMe"]) _remeberMeButton.selected = true;
    }
    return _remeberMeButton;
}

- (UIButton *)forgetPasswordButton {
    if (!_forgetPasswordButton) {
        _forgetPasswordButton = [[UIButton alloc] initWithFrame:CGRectMake(ScreenWidth-52-50, CGRectGetMaxY(self.passwordTF.frame), 60, 32)];
        [_forgetPasswordButton setTitle:@"忘记密码" forState:UIControlStateNormal];
        [_forgetPasswordButton setTitleColor:hexColor(333333) forState:UIControlStateNormal];
        _forgetPasswordButton.titleLabel.font = [UIFont fontWithName:@"SourceHanSansCN-Regular" size:10];
        [_forgetPasswordButton addTarget:self action:@selector(forgetPasswordButtonClick) forControlEvents:UIControlEventTouchUpInside];
    }
    return _forgetPasswordButton;
}

- (LSWaveView *)firstWaveView {
    if (!_firstWaveView) {
        _firstWaveView = [[LSWaveView alloc] initWithFrame:CGRectMake(0, 240+(SafeAreaTopHeight-64+20)-WaveViewHeight, ScreenWidth, WaveViewHeight) withWaveColor:UIColor.whiteColor andWaveA:WaveViewHeight/2 andWaveW:0.7/30.0 andOffsetX:3 andCurrentK:WaveViewHeight/2 andWavesSpeed:0.03/M_PI andWavesWidth:ScreenWidth];
        _firstWaveView.tag = 1001;
    }
    return _firstWaveView;
}

- (LSWaveView *)secondWaveView {
    if (!_secondWaveView) {
        _secondWaveView = [[LSWaveView alloc] initWithFrame:CGRectMake(0, 240+(SafeAreaTopHeight-64+20)-SecondWaveViewHeight, ScreenWidth, SecondWaveViewHeight) withWaveColor:hexColorAlpha(91D0F9, 0.6) andWaveA:SecondWaveViewHeight/2 andWaveW:0.7/30.0 andOffsetX:4.5 andCurrentK:SecondWaveViewHeight/2 andWavesSpeed:0.05/M_PI andWavesWidth:ScreenWidth];
        _secondWaveView.tag = 1002;
    }
    return _secondWaveView;
}

- (LSWaveView *)thirdWaveView {
    if (!_thirdWaveView) {
        _thirdWaveView = [[LSWaveView alloc] initWithFrame:CGRectMake(0, 240+(SafeAreaTopHeight-64+20)-ThirdWaveViewHeight, ScreenWidth, ThirdWaveViewHeight) withWaveColor:hexColorAlpha(ffffff, 0.3) andWaveA:ThirdWaveViewHeight/2 andWaveW:0.7/30.0 andOffsetX:14 andCurrentK:ThirdWaveViewHeight/2 andWavesSpeed:0.04/M_PI andWavesWidth:ScreenWidth];
        _thirdWaveView.tag = 1003;
    }
    return _thirdWaveView;
}

- (LSWaveView *)fourthWaveView {
    if (!_fourthWaveView) {
        _fourthWaveView = [[LSWaveView alloc] initWithFrame:CGRectMake(0, 240+(SafeAreaTopHeight-64+20)-FourthWaveViewHeight, ScreenWidth, FourthWaveViewHeight) withWaveColor:hexColorAlpha(ffffff, 0.3) andWaveA:FourthWaveViewHeight/2 andWaveW:0.7/30.0 andOffsetX:12 andCurrentK:FourthWaveViewHeight/2 andWavesSpeed:0.035/M_PI andWavesWidth:ScreenWidth];
        _fourthWaveView.tag = 1004;
    }
    return _fourthWaveView;
}

- (void)dealloc {
    NSLog(@"登录控制器释放了");
}

/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
